package com.example.jdbcsamples.program;

import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 
 * @author Bora SAYINER
 * @since Feb 1, 2015 10:33:23 AM
 * @version 1.0.0
 */
public class Driver {

	private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
	private static final String DB_USER_NAME = "bp";
	private static final String DB_PASSWORD = "ap";

	public static void main(String[] args) {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD);
			statement = connection.createStatement();
			final String sqlCmd = "SELECT * FROM vendors";
			resultSet = statement.executeQuery(sqlCmd);
			while (resultSet.next()) {
				int index = resultSet.getRow();
				int vendorId = resultSet.getInt("vendor_id");
				String vendorName = resultSet.getString("vendor_name");
				String vendorAddress = resultSet.getString("vendor_address1");
				String vendorCity = resultSet.getString("vendor_city");
				System.out.println(index + " Vendor ID: " + vendorId + " Vendor Name: " + vendorName
						+ " Vendor Address: " + vendorAddress + " Vendor City: " + vendorCity);
			}
		} catch (SQLException e) {
			printSqlError(e);
		} finally {
			try {
				if (resultSet != null) resultSet.close();
				if (statement != null) statement.close();
				if (connection != null) connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void printSqlError(SQLException exception) {
		System.err.println("Error message: " + exception.getMessage());
		System.err.println("Error code: " + exception.getErrorCode());
		System.err.println("Sql state: " + exception.getSQLState());
	}

}
